<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\AddPermissionRequest;
use App\Models\Permission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;

/**
 * 权限控制器
 * Class PermissionController
 * @package App\Http\Controllers\Admin
 */
class PermissionController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        $data = Permission::get()->toArray();
        $data = subMenu($data);
        return view('admin.permission.index', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        // 顶级菜单
        $data = Permission::where('pid', 0)->get(['id', 'name']);
        return view('admin.permission.create', compact('data'));
    }

    /**
     * Store a newly created resource in storage.
     * @param  \Illuminate\Http\Request $request
     * @return Response
     */
    public function store(AddPermissionRequest $request)
    {
        $data = $request->except('_token');
        $data['route'] = is_null($data['route']) ? '' : $data['route'];
        $res = Permission::create($data);
        if ($res) {
            return response()->json(['status' => 0, 'msg' => '成功']);
        }
        return response()->json(['status' => 1, 'msg' => '失败']);
    }

    /**
     * Display the specified resource.
     * @param  int $id
     * @return Response
     */
    public function show($id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Response
     */
    public function edit(int $id)
    {
        // 顶级菜单
        $data = Permission::where('pid', 0)->get(['id', 'name']);
        $permission = Permission::find($id);
        return view('admin.permission.edit', compact('permission', 'data'));
    }

    /**
     * Update the specified resource in storage.
     * @param  \Illuminate\Http\Request $request
     * @param Permission $permission
     * @return array
     */
    public function update(Request $request, Permission $permission)
    {
        $data = $request->all();
        $res = $permission->update($data);
        if ($res) {
            return ['status' => 0, 'msg' => '成功'];
        }
        return ['status' => 1, 'msg' => '失败'];
    }

    /**
     * Remove the specified resource from storage.
     * @param Permission $permission
     * @return array
     * @throws \Exception
     */
    public function destroy(Permission $permission)
    {
        $res = $permission->delete();
        if ($res) {
            return ['status' => 0, 'msg' => '成功'];
        }
        return ['status' => 1, 'msg' => '失败'];
    }
}
